package com.ikangtai.shecare.personal;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncMACAddressForBind;
import com.ikangtai.shecare.common.eventBusMsg.BindMsg;
import com.ikangtai.shecare.common.eventBusMsg.ConnectStateMsg;
import com.ikangtai.shecare.common.eventBusMsg.TemperUploadMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncMACAddressForBindMsg;
import com.ikangtai.shecare.common.services.ble.BLEThermometerService;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DeviceInfo;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDeviceVersion2Activity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private ImageView stepFirstImage;
    private ImageView stepSecondImage;
    private Button bindBtn;
    private String typeBind;
    private static String MACAddress;
    private DeviceInfo deviceInfo;
    private DBManager dbManager;

    private boolean sign = false;
    private static BLEThermometerService mBLEThermometerService = null;
    private static boolean mScanning;
    private final long SCAN_PERIOD = 5000L;
    private BluetoothDevice mDevice = null;
    private static String action;
    private int scanSign = 0;
    private boolean mConnected = false;// 连接
    private int readnum_flag1 = 0;
    public final String DATABASE = "Database";
    private int THERMOMETER_CONNECTED_NUM = 0;
    private int THERMOMETER_CONNECTED_END_NUM = 0;
    private boolean isBLERegistered = false;
    private ProgressDialog progressDialog;
    String hardwareVersion = null;

    private static final int CHECKBIND_SUCCESS = 0;
    private static final int CHECKBIND_FAILURE = 1;
    private static final int BIND_REPETE = 2;
    private static final int BIND_SUCCESS = 3;
    private static final int BIND_FAILURE = 4;
    BindMsg bindMsg = new BindMsg();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_device_version2);
        ActivityCollector.addActivity(this);
        Intent intent = getIntent();
        typeBind = intent.getStringExtra("type");
        if (typeBind.equals("register"))
            App.saveUserPreference("bindType", typeBind);
        App.isBindActivityActive = true;
        deviceInfo = new DeviceInfo(this);
        dbManager = new DBManager(this);
        EventBus.getDefault().register(this);
        initView();
        initBluetooth();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });

        stepFirstImage = (ImageView) findViewById(R.id.stepFirstState2);
        stepSecondImage = (ImageView) findViewById(R.id.stepSecondState2);
        bindBtn = (Button) findViewById(R.id.version2_bind_btn);
        bindBtn.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checkBind(MACAddress);
            }
        });
        bindBtn.setClickable(false);
    }

    private void checkBind(String MACAddress) {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "hardware/checkIsBinding.json?MACAddress=" + MACAddress;

        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {

                bindMsg.setRespCode(CHECKBIND_FAILURE);
                EventBus.getDefault().post(bindMsg);
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    JSONObject respJSONObj = new JSONObject(response.body().string());
                    int respCode = respJSONObj.getInt("code");
                    AppLog.e("" + respCode);
                    if (230 == respCode) {
                        bindMsg.setRespCode(CHECKBIND_SUCCESS);
                        EventBus.getDefault().post(bindMsg);
                    } else if (231 == respCode) {
                        bindMsg.setRespCode(BIND_REPETE);
                        EventBus.getDefault().post(bindMsg);
//                            Looper.prepare();
//                            Toast.makeText(getApplicationContext(), "该设备已被绑定过!请先解除绑定。", Toast.LENGTH_SHORT).show();
//                            App.saveUserPreference("MACAddress", MyDeviceVersion2Activity.this.MACAddress);
//                            Looper.loop();
                    }
                } catch (JSONException e) {

                    bindMsg.setRespCode(CHECKBIND_FAILURE);
                    EventBus.getDefault().post(bindMsg);
                    e.printStackTrace();
                }
            }
        });

    }

    private void syncMACAddressAndBind() {
        if (InternetUtil.hasInternet()) {
            SyncMACAddressForBindMsg syncMACAddressForBindMsg = new SyncMACAddressForBindMsg();
            syncMACAddressForBindMsg.setMacAddress(MACAddress);
            syncMACAddressForBindMsg.setOSType(deviceInfo.getPhoneVersion());
            SyncMACAddressForBind syncMACAddress = new SyncMACAddressForBind(this, syncMACAddressForBindMsg);
            syncMACAddress.syncMACAddressForBindWithNetwork();
        } else {
            bindMsg.setRespCode(BIND_FAILURE);
            EventBus.getDefault().post(bindMsg);
            Toast.makeText(this, R.string.network_anomalies, Toast.LENGTH_SHORT).show();
        }
    }

    private void bindFromServer() {

        AppLog.i("MyDeviceVersion2Activity 准备 bindFromServer！");

        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date(time);
        String dateStr = format.format(date1);
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "hardware/bindingThermometer.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("MACAddress", MACAddress);
            okHttpClient.add("OSType", deviceInfo.getPhoneVersion());
            okHttpClient.add("location", "");
            okHttpClient.add("bindingTime", dateStr);
            if(null != hardwareVersion){
                okHttpClient.add("hardwareVersion", hardwareVersion);
            }
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    bindMsg.setRespCode(BIND_FAILURE);
                    EventBus.getDefault().post(bindMsg);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        if (200 == respCode) {
                            bindMsg.setRespCode(BIND_SUCCESS);
                            EventBus.getDefault().post(bindMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            bindFromServer();
                        } else {
                            bindMsg.setRespCode(BIND_FAILURE);
                            EventBus.getDefault().post(bindMsg);
                        }
                    } catch (JSONException e) {
                        bindMsg.setRespCode(BIND_FAILURE);
                        EventBus.getDefault().post(bindMsg);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            bindMsg.setRespCode(BIND_FAILURE);
            EventBus.getDefault().post(bindMsg);
            e.printStackTrace();
        }
    }

    @Subcriber
    private void syncMACAddressForBind(SyncMACAddressForBindMsg syncMACAddressForBindMsg) {
        bindFromServer();
    }

    @Subcriber
    private void dealRegisterMsg(BindMsg bindMsg) {

        int eventBusCode = bindMsg.getRespCode();
        switch (eventBusCode) {

            case CHECKBIND_SUCCESS:
                AppLog.i("MyDeviceVersion2Activity CHECKBIND_SUCCESS");
                //Toast.makeText(getApplicationContext(), "绑定中!", Toast.LENGTH_SHORT).show();
                mBLEThermometerService.bindThermometer();
                if (typeBind.equals("bindThermometer"))
                    syncMACAddressAndBind();
                else if (typeBind.equals("register")) {
                    progressDialog.setMessage(getString(R.string.attach_success));
                    //Toast.makeText(getApplicationContext(), R.string.attach_success, Toast.LENGTH_SHORT).show();
                    (new Handler()).postDelayed(new Runnable() {
                        @Override
                        public synchronized void run() {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                            Intent intent = new Intent(MyDeviceVersion2Activity.this, RegisterActivity.class);
                            intent.putExtra("MACAddress", MyDeviceVersion2Activity.this.MACAddress);
                            startActivity(intent);
                            ActivityCollector.finishAll();
                        }
                    }, 1500);

                }
                break;
            case CHECKBIND_FAILURE:
                AppLog.i("MyDeviceVersion2Activity CHECKBIND_FAILURE");
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                //Toast.makeText(getApplicationContext(), "请求server异常!", Toast.LENGTH_SHORT).show();
                break;
            case BIND_REPETE:
                AppLog.i("MyDeviceVersion2Activity BIND_REPETE");
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                Toast.makeText(getApplicationContext(), R.string.hardware_attached_unattach, Toast.LENGTH_SHORT).show();
                break;
            case BIND_SUCCESS:
                AppLog.i("MyDeviceVersion2Activity BIND_SUCCESS");
                progressDialog.setMessage(getString(R.string.attach_success));
                //Toast.makeText(getApplicationContext(), getString(R.string.attach_success), Toast.LENGTH_SHORT).show();
                App.saveUserPreference("bindState", "binded");
                dbManager.updateUserPreference(App.userName, "macAddress", MACAddress, "isMACAddressSynced", 1);
                App.memory_preference_macAddress = MACAddress;
                ConnectStateMsg connectStateMsg = new ConnectStateMsg();
                connectStateMsg.setRespCode(0);
                EventBus.getDefault().post(connectStateMsg);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                        temperUploadMsg.setRespCode(3);
                        EventBus.getDefault().post(temperUploadMsg);
                        ActivityCollector.finishAll();
                    }
                }, 1500);
                break;
            case BIND_FAILURE:
                AppLog.i("MyDeviceVersion2Activity BIND_FAILURE");
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                dbManager.updateUserPreference(App.userName, "macAddress", MACAddress, "isMACAddressSynced", 0);
                Toast.makeText(getApplicationContext(), R.string.attach_service_error, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

    }

    private void saveConnectTime() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        Date date1 = new Date(time);
        String dateStr = format.format(date1);
        dbManager.updateUserPreference(App.userName, "lastConnectTime", dateStr);
        App.memory_preference_lastConnectTime = dateStr;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    private void initBluetooth() {
        // 绑定服务
        Intent gattServiceIntent = new Intent(MyDeviceVersion2Activity.this, BLEThermometerService.class);
        sign = getApplicationContext().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.binding));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onResume() {

        THERMOMETER_CONNECTED_NUM = 0;
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        //adapter不等于null，说明本机有蓝牙设备
        if (adapter != null) {
            AppLog.e("本机有蓝牙设备！");
            //如果蓝牙设备未开启
            if (adapter.isEnabled()) {
                if (mBLEThermometerService != null) {
                    stepFirstImage.setImageResource(R.drawable.personal_my_device_bind_ok);
                    operateThermometerScan(true);// 温度计扫描操作开始
                }
            } else {
                stepFirstImage.setImageResource(R.drawable.personal_my_device_bind_false);
            }
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        isBLERegistered = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //App.isBindActivityActive = false;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        AppLog.e("-----onDestroy");
        App.isBindActivityActive = false;
        operateThermometerScan(false);// 温度计扫描操作停止
        if (mGattUpdateReceiver != null && isBLERegistered == true) {
            unregisterReceiver(mGattUpdateReceiver);// 不注册广播接收器
            isBLERegistered = false;
        }
        if (sign && mServiceConnection != null) {
            getApplicationContext().unbindService(mServiceConnection);//解绑服务
            AppLog.e("onDestroy unbindService");
            sign = false;
        }
        getApplicationContext().stopService(new Intent(MyDeviceVersion2Activity.this, BLEThermometerService.class));
        ActivityCollector.removeActivity(this);
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @SuppressLint("NewApi")
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            AppLog.e("CalendarActivity onServiceConnected");
            mBLEThermometerService = ((BLEThermometerService.LocalBinder) service).getService();
            // initialize初始化
            if (!mBLEThermometerService.initialize()) {// 如果温度计服务不初始化
                Toast.makeText(MyDeviceVersion2Activity.this, getString(R.string.bluetooth_unused), Toast.LENGTH_SHORT).show();
            } else {
                mBLEThermometerService.openBluetooth(MyDeviceVersion2Activity.this);
                if (BluetoothAdapter.getDefaultAdapter().isEnabled())
                    stepFirstImage.setImageResource(R.drawable.personal_my_device_bind_ok);
                operateThermometerScan(true);// 温度计扫描操作打开
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBLEThermometerService = null;
        }
    };

    // 温度计扫描操作
    private void operateThermometerScan(final boolean enable) {
        AppLog.e("ThermometerService come in operateThermometerScan");
        if (mBLEThermometerService == null) {// 如果蓝牙温度计服务没有被绑定，就提示
            Toast.makeText(this, R.string.bluetooth_init, Toast.LENGTH_SHORT).show();
            return;
        }

        if (enable) {
            AppLog.e("CalendarActivity begin operateThermometerScan");
            if (mBLEThermometerService.thermometers.size() == 0) {
                mScanning = mBLEThermometerService.scanThermometers(mLeScanCallback);
            }
        } else {
            mScanning = false;
            mBLEThermometerService.stopScanThermometers(mLeScanCallback); // 停止扫描温度计
        }
    }

    @SuppressLint("NewApi")
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            int i = 0;
            MACAddress = device.getAddress().toString().trim();
            AppLog.e(" LeScanCallback MACAddress:" + MACAddress);
            if (true) {
                AppLog.e("CalendarActivity LeScanCallback ThermometerSensor0");
                mBLEThermometerService.thermometers.add(device);
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ((mBLEThermometerService.autoConnect)
                            && (mBLEThermometerService.thermometers.size() > 0)) {
                        mBLEThermometerService.stopScanThermometers(mLeScanCallback);
                        mDevice = BluetoothAdapter.getDefaultAdapter()
                                .getRemoteDevice(device.getAddress());
                        AppLog.e("CalendarActivity LeScanCallback connectThermometer");
                        mBLEThermometerService.connectThermometer(mDevice
                                .getAddress());
                    }
                }
            });
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            AppLog.e(" MACAddress:" + MACAddress);
            if(null == MACAddress) return;
            action = intent.getAction();
            AppLog.e("onReceive action=" + action);
            if (BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName().equals(action)) {// 如果找到温度计的信息与程序定义的温度计信息一致
            }
            if (BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED.getName().equals(action)) {// 连接成功
                updateConnectInfo();
            } else if (BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED.getName()
                    .equals(action)) {// 断开连接温度计
                AppLog.e("THERMOMETER_DISCONNECTED");
                updateDisconnectInfo();
            } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND.getName()
                    .equals(action)) {
                handleTimeSyncResult(intent);
            } else if (BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND.getName()
                    .equals(action)) {
                //handleCloseThermomter(intent);
            } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN.getName()
                    .equals(action)) {
                if(intent.getIntExtra("isInBind", 0) == 1) {
                    AppLog.e("TEMPERATURE_MEASUREMENT_OPEN");
                    mBLEThermometerService.syncCurrentTime();
                    (new Handler()).postDelayed(new Runnable() {
                        @Override
                        public synchronized void run() {
                            mBLEThermometerService.readFirmwareRevision();
                            bindBtn.setBackground(getResources().getDrawable(R.drawable.personal_my_device_bind_button_bg_selectable));
                            bindBtn.setClickable(true);
                            checkBind(MACAddress);
                        }
                    }, 200);
                }
            } else if (BLEThermometerService.ThermometerMessage.BIND_PHONE_FOUND.getName()
                    .equals(action)) {
//                handleBindPhoneResult(intent);
            } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ.getName().equals(action)) {
                hardwareVersion = intent.getStringExtra(BLEThermometerService.ThermometerDataTag.FIRMWARE_REVISION_DATA.getName());
                AppLog.e("HARDWARE_REVISION_READ" + hardwareVersion);
                App.hardwareRevision = Integer.valueOf(hardwareVersion.substring(0, 1));
                App.saveUserPreference("hardwareRevision", App.hardwareRevision);
            } else if (BLEThermometerService.ThermometerMessage.MEASUREMENT_INTERVAL_FOUND.getName()
                    .equals(action)) {
                AppLog.e("MEASUREMENT_INTERVAL_FOUND");
            } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ.getName()
                    .equals(action)) {

            } else if (BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                    .getName().equals(action)) {
                operateThermometerScan(true);
            }

        }

        private void handleBindPhoneResult(Intent intent) {
            int result = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.BIND_PHONE_DATA.getName(), 0);
//            if (1 == result)
//                Toast.makeText(CalendarActivity.this, "绑定失败！", Toast.LENGTH_LONG).show();
            if (2 == result)
                Toast.makeText(MyDeviceVersion2Activity.this, getString(R.string.attach_success), Toast.LENGTH_LONG).show();
//                if(typeBind.equals("bindThermometer")) bindFromServer();
//            if (3 == result)
//                Toast.makeText(CalendarActivity.this, "解绑失败！", Toast.LENGTH_LONG).show();
            if (4 == result)
                Toast.makeText(MyDeviceVersion2Activity.this, getString(R.string.unattch_success), Toast.LENGTH_LONG).show();
        }


        private void handleCloseThermomter(Intent intent) {
            int result = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.CLOSE_THERMOMETER_DATA.getName(), 0);
            if (3 == result)
                Toast.makeText(MyDeviceVersion2Activity.this, R.string.close_success, Toast.LENGTH_LONG).show();
            if (4 == result) {
                Toast.makeText(MyDeviceVersion2Activity.this, R.string.synchronization_fail, Toast.LENGTH_LONG).show();
            }
        }

        private void updateDisconnectInfo() {
            mConnected = false;
            stepSecondImage.setImageResource(R.drawable.personal_my_device_bind_false);
            bindBtn.setBackground(getResources().getDrawable(R.drawable.personal_my_device_bind_button_bg));
            bindBtn.setClickable(false);
            THERMOMETER_CONNECTED_NUM = 0;
            THERMOMETER_CONNECTED_END_NUM = 0;
            (new Handler()).postDelayed(new Runnable() {
                @Override
                public synchronized void run() {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                }
            }, 1500);

            if (scanSign == 0) {
                scanSign = 1;
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        scanSign = 0;
                        operateThermometerScan(true);// 温度计扫描操作打开
                    }
                }, SCAN_PERIOD);
                AppLog.e("THERMOMETER_DISCONNECTED postDelayed operateThermometerScan");
            }
        }

        private void updateConnectInfo() {
            mConnected = true;
            saveConnectTime();
            stepSecondImage.setImageResource(R.drawable.personal_my_device_bind_ok);
            if (THERMOMETER_CONNECTED_NUM == 0) {
                if(null != MACAddress)
                showProgressDialog();
                //progressDialog.setMessage(getString(R.string.binding));

                THERMOMETER_CONNECTED_NUM = THERMOMETER_CONNECTED_NUM + 1;
            } else {
                THERMOMETER_CONNECTED_NUM = THERMOMETER_CONNECTED_NUM + 1;
            }
        }

        private void handleTimeSyncResult(Intent intent) {
            int result = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.SYNC_TIME_DATA.getName(), 0);
//            if (1 == result)
//                Toast.makeText(MyDeviceVersion2Activity.this, "同步时间成功！", Toast.LENGTH_LONG).show();
//            if (2 == result)
//                Toast.makeText(MyDeviceVersion2Activity.this, "同步时间失败！", Toast.LENGTH_LONG).show();
        }
    };

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED
                .getName());
        intentFilter
                .addAction(BLEThermometerService.ThermometerMessage.RSSI_DATA_AVAILABLE.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.HARDWARE_REVISION_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.BIND_PHONE_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND
                .getName());

        return intentFilter;
    }

}
